/*!
 * SystemsInfluenza.org Website v2.0
 * Copyright(c) 2006-2012 Institute for Systems Biology, Seattle, Washington, USA
 * codefor@systemsbiology.org
 * http://www.gnu.org/licenses/lgpl.html
 * Author: Hector Rovira
 * Description:  Draws an Ext JS grid based on annotations.tsv
 */
ColumnHelper = Ext.extend(Object, {
    linkColumns: [],
    columnSpecs: {},

    constructor: function(spec) {
        this.linksPath = "/repositories/datasets/file" + spec.path + "/";

        if (spec.downloadsColumn) {
            this.downloadsColumn = spec.downloadsColumn;
        }
        if (spec.linkColumns && spec.linkColumns.length) {
            this.linkColumns = spec.linkColumns;
        }
        if (spec.columnSpecs) {
            this.columnSpecs = spec.columnSpecs;
        }
    },

    isDownloadsColumn: function(column) {
        return (column == this.downloadsColumn);
    },

    isLinkColumn: function(column) {
        return (this.linkColumns.length && (this.linkColumns.indexOf(column) >= 0));
    },

    getColumnWidth: function(column) {
        var colspec = this.columnSpecs[column];
        if (colspec && colspec.width) {
            return colspec.width;
        }
        return 100;
    },

    isSortable: function(column) {
        if (this.isDownloadsColumn(column)) {
            return false;
        }
        return !this.isLinkColumn(column);
    },

    getValue: function(fieldname, cell) {
        if (this.isDownloadsColumn(fieldname)) {
            return this.getDownloadsCell(cell);
        } else if (this.isLinkColumn(fieldname)) {
            return this.getLinksCell(cell);
        } else {
            return cell;
        }
    },

    getDownloadsCell: function(cell) {
        if (cell.indexOf(",") > 0) {
            var html = "";
            Ext.each(cell.split(","), function(f) {
                html += '<li><a href="' + this.linksPath + f + '">' + f + '</a></li>'
            }, this);
            return "<ul>" + html + "</ul>";
        }

        return '<a href="' + this.linksPath + cell + '" onclick="trackDownload(this); return true;">' + cell + '</a>';
    },

    getLinksCell: function(cell) {
        if (cell && cell != "NA") {
            return '<a href="' + cell + '" target="_blank">' + cell + '</a>';
        }
        return cell;
    },

    orderFields: function(items, fields) {
        var orderedItems = [];
        var unorderedItems = [];

        Ext.each(items, function(item) {
            var colspec = this.columnSpecs[item.originalKey];
            if (colspec && colspec.order != null) {
                orderedItems[colspec.order] = item;
            } else {
                unorderedItems[unorderedItems.length] = item;
            }
        }, this);

        var appendFn = function(item) {
            fields[fields.length] = item;
        };
        Ext.each(orderedItems, appendFn);
        Ext.each(unorderedItems, appendFn);
    }
});

AnnotationsGrid = Ext.extend(Object, {

    constructor: function(contentEl, config, agconfig) {
        this.contentEl = contentEl;
        this.columnHelper = new ColumnHelper(config);
        this.agconfig = agconfig ? agconfig : {};
        this.downloadUrl = "/repositories/datasets/contents" + config.path + "/annotations.tsv";
        this.archiveUrl = "/repositories/datasets/contents" + config.path + "/files.zip";

        Ext.Ajax.request({
            url: "/repositories/datasets/query" + config.path + "/annotations.tsv",
            method: "GET",
            params: {
                "tqx": "out:json_array"
            },
            success: this.load,
            scope: this
        });
    },

    load: function(response) {
        var fields = [];
        var data = [];

        var jsonArray = Ext.util.JSON.decode(response.responseText);
        if (jsonArray && jsonArray.length) {
            this.setColumnHeaders(jsonArray[0], fields);
            Ext.each(jsonArray, function(item) {
                this.addRow(item, fields, data);
            }, this);
        }

        var gridConfig = Ext.apply({
            store: new Ext.data.ArrayStore({ fields: fields, data: data, id: Ext.id() }),
            columns: fields,
            stripeRows: true,
            columnLines: true,
            frame:true,
            collapsible: false,
            animCollapse: false,
            renderTo: this.contentEl,
            tbar: [
                {
                    text: "Download Annotations",
                    handler: function() {
                        document.location = this.downloadUrl;
                    },
                    scope: this
                },
                "-",
                {
                    text: "Download Files (zip)",
                    handler: function() {
                        document.location = this.archiveUrl;
                    },
                    scope: this
                }
            ]
        }, this.agconfig);

        new Ext.grid.GridPanel(gridConfig);
    },

    setColumnHeaders: function(firstItem, fields) {
        var items = [];
        for (var key in firstItem) {
            if (firstItem.hasOwnProperty(key)) {
                var headerId = Ext.id();
                items[items.length] = {
                    id: headerId,
                    name: headerId,
                    dataIndex: headerId,
                    originalKey: key,
                    header: key.trim(),
                    sortable: this.columnHelper.isSortable(key),
                    menuDisabled: true,
                    width: this.columnHelper.getColumnWidth(key)
                };
            }
        }

        this.columnHelper.orderFields(items, fields);
    },

    addRow: function(item, fields, data) {
        var rowData = [];
        Ext.each(fields, function(f) {
            rowData[rowData.length] = this.columnHelper.getValue(f.originalKey, item[f.originalKey]);
        }, this);
        data[data.length] = rowData;
    }
});
